// Copyright 2012 Google Inc. All Rights Reserved.
package com.valohyd.android_utils.tabs;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

/**
 * Convenience helper to build a set of tabs for a {@link TabCompatActivity}. To use this class,
 * extend {@link TabCompatActivity} and:
 *
 * Call {@link TabCompatActivity#getTabHelper()}, returning a {@link TabHelper}.
 *
 * Create a {@link CompatTabListener}.
 *
 * Call {@link TabHelper#newTab(String)} to create each tab.
 *
 * Call CompatTab.setText().setIcon().setTabListener() to set up your tabs.
 *
 * Call {@link TabHelper#addTab(CompatTab)} for each tab, and you're done.
 */
public class TabHelper {

    protected SherlockFragmentActivity mActivity;
    private ActionBar mActionBar;

    public TabHelper(SherlockFragmentActivity activity) {
        mActivity = activity;
    }
 
    protected void setUp() {
        if (mActionBar == null) { 
            mActionBar = mActivity.getSupportActionBar();
            mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        }
    }

    public CompatTab newTab(String tag){
        return new CompatTab(mActivity, tag);
    }
    
    public void addTab(CompatTab tab) {
        String tag = tab.getTag();

        // Check to see if we already have a fragment for this tab, probably
        // from a previously saved state.  If so, deactivate it, because our
        // initial state is that a tab isn't shown.
        SherlockFragment fragment = (SherlockFragment)mActivity.getSupportFragmentManager().findFragmentByTag(tag);
        tab.setFragment(fragment);

        if (fragment != null && !fragment.isDetached()) {
            FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
            ft.detach(fragment);
            ft.commit();
        }

        if (tab.getCallback() == null) {
            throw new IllegalStateException("CompatTab must have a CompatTabListener");
        }

        // We know tab is a CompatTabHoneycomb instance, so its
        // native tab object is an ActionBar.Tab.
        mActionBar.addTab((ActionBar.Tab) tab.getTab());
    }

    protected void onSaveInstanceState(Bundle outState) {
        int position = mActionBar.getSelectedTab().getPosition();
        outState.putInt("tab_position", position);
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        int position = savedInstanceState.getInt("tab_position");
        mActionBar.setSelectedNavigationItem(position);
    }

    public int getCurrentTab() {
        return mActionBar.getSelectedTab().getPosition();
    }

    public void setCurrentTab(int i) {
        mActionBar.getTabAt(i).select();        
    }
}